import { login, logout, getInfo } from '@neu/biz-core/api/user'
import { getToken, setToken, removeToken } from '@neu/biz-core/utils/auth'
import router, { resetRouter } from '@neu/biz-core/router'
import StompClient from '@neu/biz-core/utils/stomp-client'
import app from './app'

const state = {
  token: getToken(),
  id: '',
  name: '',
  avatar: '',
  introduction: '',
  roles: [],
  menus: [],
  buttons: [],
  orgs: [],
  modules: []
}

const mutations = {
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_ID: (state, id) => {
    state.id = id
  },
  SET_INTRODUCTION: (state, introduction) => {
    state.introduction = introduction
  },
  SET_NAME: (state, name) => {
    state.name = name
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar
  },
  SET_ROLES: (state, roles) => {
    state.roles = roles
  },
  SET_MENUS: (state, menus) => {
    state.menus = menus
  },
  SET_BUTTONS: (state, buttons) => {
    state.buttons = buttons
  },
  SET_ORGS: (state, orgs) => {
    state.orgs = orgs
  },
  SET_MODULES: (state, modules) => {
    state.modules = modules
  }
}

const actions = {
  // user login
  login({ commit }, userInfo) {
    const { username, password } = userInfo
    return new Promise((resolve, reject) => {
      login({ username: username.trim(), password: password }).then(response => {
        const { data } = response
        commit('SET_TOKEN', data)
        setToken(data)
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  // get user info
  getInfo({ commit, state, dispatch }) {
    return new Promise((resolve, reject) => {
      getInfo().then(response => {
        const { data } = response

        if (!data) {
          reject('Verification failed, please Login again.')
        }

        const { roles, name, userId, permissions, orgs } = data
        const hisMenus = new Set()
        const hisButtons = new Set()
        permissions.menus.forEach(m => hisMenus.add(m))
        permissions.actions.forEach(m => hisButtons.add(m))
        roles.forEach(r => {
          r.permissions.menus.forEach(m => hisMenus.add(m))
          r.permissions.actions.forEach(m => hisButtons.add(m))
        })

        // roles must be a non-empty array
        if (!roles || roles.length <= 0) {
          reject('getInfo: roles must be a non-null array!')
        }
        commit('SET_ROLES', roles.map(it => it.role))
        commit('SET_ID', userId)
        commit('SET_NAME', name)
        commit('SET_MENUS', [...hisMenus])
        commit('SET_BUTTONS', [...hisButtons])
        commit('SET_ORGS', [...orgs])
        // commit('SET_AVATAR', avatar)
        // commit('SET_INTRODUCTION', introduction)
        if (app.state.wsEnabled) {
          StompClient.connect()
        }
        // if (app.state.autoRun && app.state.autoRun.length > 0) {
        //   app.state.autoRun.forEach(auto => dispatch(auto, {}, { root: true }))
        // }
        resolve(roles.some(r => r.role === 'admin') ? 'all' : [...hisMenus])
      }).catch(error => {
        reject(error)
      })
    })
  },

  // user logout
  logout({ commit, state, dispatch }) {
    return new Promise((resolve, reject) => {
      logout(state.token).then(() => {
        commit('SET_TOKEN', '')
        commit('SET_ROLES', [])
        commit('SET_MENUS', [])
        commit('SET_BUTTONS', [])
        commit('SET_ORGS', [])
        removeToken()
        resetRouter()
        StompClient.disconnect()
        // reset visited views and cached views
        // to fixed https://github.com/PanJiaChen/vue-element-admin/issues/2485
        dispatch('tagsView/delAllViews', null, { root: true })

        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  // remove token
  resetToken({ commit }) {
    return new Promise(resolve => {
      commit('SET_TOKEN', '')
      commit('SET_ROLES', [])
      commit('SET_MENUS', [])
      commit('SET_BUTTONS', [])
      commit('SET_ORGS', [])
      removeToken()
      resolve()
    })
  },

  // dynamically modify permissions
  changeRoles({ commit, dispatch }, role) {
    return new Promise(async resolve => {
      const token = role + '-token'

      commit('SET_TOKEN', token)
      setToken(token)

      const { roles } = await dispatch('getInfo')

      resetRouter()

      // generate accessible routes map based on roles
      const accessRoutes = await dispatch('permission/generateRoutes', roles, { root: true })

      // dynamically add accessible routes
      router.addRoutes(accessRoutes)

      // reset visited views and cached views
      dispatch('tagsView/delAllViews', null, { root: true })

      resolve()
    })
  },

  setModules({ commit }, modules) {
    commit('SET_MODULES', modules)
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
